package com.chcit.mobile.mvp.common.presenter;

import android.app.Application;
import com.alibaba.fastjson.JSONObject;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.app.exception.BaseException;
import com.chcit.mobile.common.SPDErrorHandle;
import com.chcit.mobile.mvp.common.contract.CommonContract;
import com.chcit.mobile.mvp.entity.Locator;
import com.chcit.mobile.mvp.entity.PageBean;
import com.chcit.mobile.mvp.entity.ResultBean;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.common.contract.ScanPackageContract;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.chcit.mobile.mvp.receive.Entity.AsnLineBean;
import com.chcit.mobile.mvp.receive.Entity.AsnPackageBean;
import com.chcit.mobile.mvp.receive.Entity.AsnResultBean;
import com.chcit.mobile.mvp.receive.api.QueryListInput;
import com.chcit.mobile.mvp.receive.contract.ReceiveContract;
import com.chcit.mobile.mvp.receive.model.ReceiveModel;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import javax.inject.Inject;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
import java.util.List;

@FragmentScope
public class ScanPackagePresenter extends BasePresenter<ScanPackageContract.Model, ScanPackageContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    CommonContract.Model commModel;
    @Inject
    ReceiveModel mReceiveModel;

    public boolean isError = false; //是否发生过错误，如果最后提交发生错误。返回上一个页面会刷新数据！

    @Inject
    public ScanPackagePresenter(ScanPackageContract.Model model, ScanPackageContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    /**
     * 按包装验收
     *  {asnId:"1212",asnLineId:12123,locatorId:"1212",packageNo:["2323","232323dfdf"]}
     */
    public void checkAsnPackageRecieve(JSONObject paramReq, Action action) {
        mModel.packageReceiveSubmit(paramReq)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {
                    if(resultBean.isSuccess()){
                        action.run();
                    }else{
                        String msg = resultBean.getMsg();
                        if(msg.isEmpty()){
                            msg = "未知错误！";
                        }
                        throw new BaseException(msg);
                    }

                } catch (Exception e) {
                    onError(e);
                }
            }

            @Override
            public void onError(Throwable t) {
                isError = true;
                super.onError(t);
            }
        });
    }

    /**
     * 按包装验视
     *  {asnId:"1212",asnLineId:12123,locatorId:"1212",packageNo:["2323","232323dfdf"]}
     */
    public void inspectePackageRecieve(JSONObject paramReq, Action action) {
        mModel.inspectePackageSubmit(paramReq)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {
                    if(resultBean.isSuccess()){
                        action.run();
                    }else{
                        String msg = resultBean.getMsg();
                        if(msg.isEmpty()){
                            msg = "未知错误！";
                        }
                        throw new BaseException(msg);
                    }

                } catch (Exception e) {
                    onError(e);
                }
            }

            @Override
            public void onError(Throwable t) {
                isError = true;
                super.onError(t);
            }
        });
    }

    /**
     * 按包装上架
     *  {asnId:"1212",asnLineId:12123,locatorId:"1212",packageNo:["2323","232323dfdf"]}
     */
    public void pickupAsnPackageRecieve(JSONObject paramReq, Action action) {
        mModel.pickupPackageSubmit(paramReq)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {
                    if(resultBean.isSuccess()){
                        action.run();
                    }else{
                        String msg = resultBean.getMsg();
                        if(msg.isEmpty()){
                            msg = "未知错误！";
                        }
                        throw new BaseException(msg);
                    }

                } catch (Exception e) {
                    onError(e);
                }
            }

            @Override
            public void onError(Throwable t) {
                isError = true;
                super.onError(t);
            }
        });
    }

    /**
     * 按包装退回
     *  {asnId:"1212",asnLineId:12123,locatorId:"1212",packageNo:["2323","232323dfdf"]}
     */
    public void pickbackAsnPackageRecieve(JSONObject paramReq, Action action) {
        mModel.pickbackPackageSubmit(paramReq)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {
                    if(resultBean.isSuccess()){
                        action.run();
                    }else{
                        String msg = resultBean.getMsg();
                        if(msg.isEmpty()){
                            msg = "未知错误！";
                        }
                        throw new BaseException(msg);
                    }

                } catch (Exception e) {
                    onError(e);
                }
            }

            @Override
            public void onError(Throwable t) {
                isError = true;
                super.onError(t);
            }
        });
    }

    /**
     * 按照到货通知单行和包装拒收
     *  {asnId:"1212",asnLineId:12123,rejectReason:"test",packageNo:["2323","232323dfdf"]}
     */
    public void rejectAsnPackage(JSONObject paramReq, Action action) {
        mModel.requestRejectBySubmit(paramReq)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {

                        if(resultBean.isSuccess()){
                            action.run();
                        }else{
                            String msg = resultBean.getMsg();
                            if(msg.isEmpty()){
                                msg = "未知错误！";
                            }
                            throw new BaseException(msg);
                        }

                } catch (Exception e) {
                    onError(e);
                }
            }
        });
    }

    /**
     * 按照到货通知单行和包装拒收入库
     *  {asnId:"1212",locatorId:12123,packageNo:["2323","232323dfdf"]}
     */
    public void verifyRejectAsnPackageReceive(JSONObject paramReq, Action action){
        mModel.requestBySubmit(HttpMethodContains.RECEIVE_REJECT_OK,paramReq)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {
                    if(resultBean.isSuccess()){
                        action.run();
                    }else{
                        String msg = resultBean.getMsg();
                        if(msg.isEmpty()){
                            msg = "未知错误！";
                        }
                        throw new BaseException(msg);
                    }
                } catch (Exception e) {
                    onError(e);
                }
            }
        });
    }

    /** 查询包装信息 asnId 必填
     *   拨补/拨退 入库 {page:'receive',showScaned:'Y',asnId:'121212'}
     *   （拨补/拨退）拒收 入库 {page:'rejectReceive',asnId:'121212'}
     */
    public void queryAsnPackageDetail(JSONObject paramReq, Consumer<List<PackageBean>> consumer) {
        mModel.requestOnString(HttpMethodContains.RECEIVE_PACKAGE_QUERY,paramReq)
                .map(result -> {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if(jsonObject.getBoolean("success")){
                        JSONObject data = jsonObject.getJSONObject("data");
                        if(data.getInteger("total")>0){
                            return data.getJSONArray("rows").toJavaList(PackageBean.class);
                        }else{
                            throw new BaseException("没有查询到包装信息");
                        }
                    }else {
                        String msg =jsonObject.getString("msg");
                        if(msg!=null&&!msg.isEmpty()){
                            throw new Exception(msg);
                        }else{
                            throw new Exception("未知错误！");
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                })
                .subscribe(new SPDErrorHandle<List<PackageBean>>(mErrorHandler) {
                    @Override
                    public void onNext(List<PackageBean> lists) {
                        try {
                            consumer.accept(lists);
                        } catch (Exception e) {
                            onError(e);
                        }
                    }
                });
    }

    public void getLocators(JSONObject json, Consumer<List<Locator>> onNext) {

        mModel.request(HttpMethodContains.LOCATORS,json)
                .map(jsonObject -> {
                    if(jsonObject.getBoolean("success")){
                        JSONObject data = jsonObject.getJSONObject("data");
                        if(data.getInteger("total")>0){
                            return data.getJSONArray("rows").toJavaList(Locator.class);
                        }else{
                            throw new BaseException("没有查询到货位信息");
                        }
                    }else {
                        String msg =jsonObject.getString("msg");
                        if(msg!=null&&!msg.isEmpty()){
                            throw new Exception(msg);
                        }else{
                            throw new Exception("未知错误！");
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                })
                .subscribe(new SPDErrorHandle<List<Locator>>(mErrorHandler) {
                    @Override
                    public void onNext(List<Locator> lists) {
                        try {
                            onNext.accept(lists);
                        } catch (Exception e) {
                            onError(e);
                        }
                    }
                });
    }

    public void queryListData( Consumer<List<Statu>> consumer){
        commModel.queryReasons()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new SPDErrorHandle<List<Statu>>(mErrorHandler){

                    @Override
                    public void onNext(List<Statu> bpartnerBeans) {
                        try {
                            consumer.accept(bpartnerBeans);
                        } catch (Exception e) {
                            onError(e);
                        }
                    }
                });
    }

    /**
     * 校验拣货包装
     * {pickListId:"1212",pickListJobId：121212,packageNo:["2323","232323dfdf"]}
     */
    public void verifyPickListPackage(JSONObject paramReq, Consumer<List<PackageBean>> consumer) {
        getPakcageInfo(HttpMethodContains.SHIPMENT_PACKAGE_CHECKED,paramReq,consumer);

    }
    public void getPakcageInfo(String method,JSONObject paramReq, Consumer<List<PackageBean>> consumer){
        mModel.requestOnString(method,paramReq)
                .map(result -> {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if(jsonObject.getBoolean("success")){
                        JSONObject data = jsonObject.getJSONObject("data");
                        if(data.getInteger("total")>0){
                            return data.getJSONArray("rows").toJavaList(PackageBean.class);
                        }else{
                            throw new BaseException("没有查询到包装信息");
                        }
                    }else {
                        String msg =jsonObject.getString("msg");
                        if(msg!=null&&!msg.isEmpty()){
                            throw new Exception(msg);
                        }else{
                            throw new Exception("未知错误！");
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                })
                .subscribe(new SPDErrorHandle<List<PackageBean>>(mErrorHandler) {
                    @Override
                    public void onNext(List<PackageBean> lists) {
                        try {
                            consumer.accept(lists);
                        } catch (Exception e) {
                            onError(e);
                        }
                    }
                });
    }
    /**
     *  按照包装拣货确认
     *  {pickListId:"1212",pickListJobId：121212,packageNo:["2323","232323dfdf"]}
     */
    public void pickPackage(JSONObject paramReq, Action action) {
        mModel.packagePickComfirm(paramReq)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {
                    if(resultBean.isSuccess()){
                        action.run();
                    }else{
                        String msg = resultBean.getMsg();
                        if(msg.isEmpty()){
                            msg = "未知错误！";
                        }
                        throw new BaseException(msg);
                    }

                } catch (Exception e) {
                    onError(e);
                }
            }

            @Override
            public void onError(Throwable t) {
                isError = true;
                super.onError(t);
            }
        });
    }

    /**
     * 按行取消拣货
     * pickListJobId 拣货单ID
     *  {pickListJobId:2323}
     */
    public void pickListJobCancel(int pickListJobId, Action action) {
        JSONObject params = new JSONObject();
        params.put("pickListJobId",pickListJobId);
        mModel.requestBySubmit(HttpMethodContains.SHIPMENT_REJECT_OK,params)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {
                    if(resultBean.isSuccess()){
                        action.run();
                    }else{
                        String msg = resultBean.getMsg();
                        if(msg.isEmpty()){
                            msg = "未知错误！";
                        }
                        throw new BaseException(msg);
                    }

                } catch (Exception e) {
                    onError(e);
                }
            }

            @Override
            public void onError(Throwable t) {
                isError = true;
                super.onError(t);
            }
        });
    };
    //拒收入库确认
    public void rejectReceivePackage(JSONObject paramReq, Action action) {
        mModel.packageRejctComfirm(paramReq)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {

                    if(resultBean.isSuccess()){
                        action.run();
                    }else{
                        String msg = resultBean.getMsg();
                        if(msg.isEmpty()){
                            msg = "未知错误！";
                        }
                        throw new BaseException(msg);
                    }

                } catch (Exception e) {
                    onError(e);
                }
            }
        });
    }


    public void queryAsnLineTask(QueryListInput queryListInput,Consumer<List<AsnLineBean>> consumer){
        mModel.queryAsnLineTask(queryListInput)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<List<AsnLineBean>>(mErrorHandler) {
            @Override
            public void onNext(List<AsnLineBean> resultBean) {
                try {
                    consumer.accept(resultBean);
                } catch (Exception e) {
                    onError(e);
                }
            }
        });
    }

    public void queryAsnPackageList(QueryListInput queryListInput,Consumer<List<AsnPackageBean>> consumer){
        mModel.queryAsnPackageList(queryListInput)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<List<AsnPackageBean>>(mErrorHandler) {
            @Override
            public void onNext(List<AsnPackageBean> resultBean) {
                try {
                    consumer.accept(resultBean);
                } catch (Exception e) {
                    onError(e);
                }
            }
        });
    }


    public void reCheckTaskLine(List<String> packageNos,String asnId, Action action) {
        mModel.reCheckTaskLine(packageNos,asnId)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<Boolean>(mErrorHandler) {
            @Override
            public void onNext(Boolean resultBean) {
                try {
                    action.run();

                } catch (Exception e) {
                    onError(e);
                }
            }
        });
    }

    //盲扫获取单号信息
    public void getListData(PageBean pageBean, QueryListInput input,Consumer<List<AsnResultBean>> consumer) {
        mReceiveModel.queryDataList(pageBean,input)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                })
                .subscribe(new SPDErrorHandle<List<AsnResultBean>>(mErrorHandler) {
                    @Override
                    public void onNext(List<AsnResultBean> lists) {
                        try {
                            consumer.accept(lists);
                        } catch (Exception e) {
                            onError(e);
                        }
                    }
                });
    }
}
